#include <Ogre.h>
#include<iostream>
#include "Battlecity.h"
#include "GameState.h"
#include "PlayState.h"

Battlecity::Battlecity(){

}

Battlecity::~Battlecity()
{
    delete mRoot;
}

void  Battlecity::run()
{

    mRoot = new Ogre::Root();
    this->loadResource();
    this->startup();
    // TEST
    PlayState *p = new PlayState;
    p->init();
    //mRoot->addFrameListener(p);
    //mStateVector[INTRO]=p;
    // END TEST
    setCurrentState(dynamic_cast<GameState*>(p));
    mRoot->startRendering();
}


void Battlecity::loadResource()
{
    // Load resource paths from config file
    Ogre::ConfigFile cf;
    cf.load( "resources.cfg" );

    // Go through all settings in the file
    Ogre::ConfigFile::SectionIterator itSection = cf.getSectionIterator();

    Ogre::String sSection, sType, sArch;
    while( itSection.hasMoreElements() ) {
        sSection = itSection.peekNextKey();

        Ogre::ConfigFile::SettingsMultiMap *mapSettings = itSection.getNext();
        Ogre::ConfigFile::SettingsMultiMap::iterator itSetting = mapSettings->begin();
        while( itSetting != mapSettings->end() ) {
            sType = itSetting->first;
            sArch = itSetting->second;

            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
                sArch, sType, sSection );

            ++itSetting;
        }
    }
}

int Battlecity::startup()
{
    if( !mRoot->restoreConfig() ) {
        // If there is no config file, show the configuration dialog
        if( !mRoot->showConfigDialog() ) {
            return false;
        }
    }

    // Initialise and create a default rendering window
    mWindow = mRoot->initialise( true, "BattleCity-2012" );

    // Initialise resources
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create needed scenemanagers
    mSceneManager = mRoot->createSceneManager(Ogre::ST_GENERIC,"MainSceneManager");

   //new input manager
    mInputManager = InputManager::getSingletonPtr();
    mInputManager->initialise(mWindow);


    return 0;

}




void Battlecity::setCurrentState(GameState *state){
//inizializza lo stato corrente e aggiunge lo stato come frame listener
    mCurrentState=state;
    mRoot->addFrameListener(mCurrentState);
    mInputManager->addKeyListener(mCurrentState,"Klistner");
    //mInputManager->addMouseListener(mCurrentState,"Mlistner");
}
